package cn.turing.firecontrol.admin.rest;

import cn.turing.firecontrol.admin.entity.BackChunk;
import cn.turing.firecontrol.admin.entity.BackFilelist;
import cn.turing.firecontrol.admin.service.BackFileService;
import cn.turing.firecontrol.common.exception.base.BusinessException;
import cn.turing.firecontrol.common.exception.base.ParamErrorException;
import cn.turing.firecontrol.common.msg.ObjectRestResponse;
import cn.turing.firecontrol.common.util.UUIDUtils;
import cn.turing.firecontrol.common.util.UploadUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @author tianyandong
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class UploadController {

    @Autowired
    private BackFileService backFileService;

//    @PostMapping("qiniu")
//    @ResponseBody
    public ObjectRestResponse<String> qiNiu(MultipartFile file){
        if(file == null || file.isEmpty()){
            throw new ParamErrorException("文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        Integer index = originalFilename.lastIndexOf(".");
        String key = UUIDUtils.generateShortUuid();
        if(index>0){
            key += originalFilename.substring(index);
        }
        try {
            Map<String,String> map = UploadUtil.simpleupload(file.getBytes(),key);
            String url = map.get("url");
            return new ObjectRestResponse<String>().data(url);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 上传文件
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public int postFileUpload(@ModelAttribute BackChunk chunk, HttpServletResponse response)
    {
        return backFileService.postFileUpload(chunk, response);
    }

    /**
     * 检查文件上传状态
     */
    @ApiOperation("合并文件")
    @PostMapping("/merge")
    public int merge(BackFilelist fileInfo)
    {
        log.info("调到后台");
        int i = backFileService.mergeFile(fileInfo);
        if(i == -1){
            //应对合并时断线导致的无法重新申请合并的问题
            return 1;
        }
        return 0;
    }

}
